//
//  PictureController.swift
//  新浪微博01
//
//  Created by 李国伟 on 15/12/18.
//  Copyright © 2015年 李国伟. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
let pictureCellID = "pictureCellID"
class PictureController: UIViewController {

    var urls: [NSURL]
    var indexPath: NSIndexPath
    
    //关闭控制器
    @objc private func closeController(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //保存图片
    @objc private func saveImage() {
        
        let cell = collectionView.visibleCells().first as! PictureCell
        guard let image = cell.imageView.image else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    //保存完图片的回调,根据上面函数，改编
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
        let message = error != nil ? "保存失败" : "保存成功"
        
        SVProgressHUD.showInfoWithStatus(message)
    }
    
    //自定义构造方法穿参数
    init(urls:[NSURL] ,indexPath: NSIndexPath ){
        self.urls = urls
        self.indexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //滚动到选中的cell
    override func viewDidLoad() {
        super.viewDidLoad()
        view.layoutIfNeeded()
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .CenteredHorizontally, animated: false)

    }
    
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        view = UIView(frame: rect)
        setupUI()
    }
    
    private lazy var closeButton: UIButton = UIButton(imageName: nil, title: "关闭", fontsize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(imageName: nil, title: "保存", fontsize: 14, color: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
     lazy var collectionView : UICollectionView = UICollectionView(frame: self.view.bounds , collectionViewLayout: PictureFlowLayout())
}

///  添加控件并设置约束
extension PictureController{
    
    //MARK: 添加子控件
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        closeButton.addTarget(self, action: "closeController", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "saveImage", forControlEvents: .TouchUpInside)
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(view)
            make.left.equalTo(view)
            make.right.equalTo(view)
            make.bottom.equalTo(view)
        }
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view).offset(8)
            make.bottom.equalTo(view).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view).offset(-28)
            make.bottom.equalTo(view).offset(-8)
            make.width.equalTo(100)
            make.height.equalTo(36)
        }
        
        prepareForCollectionView()
    }
}

//MARK:转场动画代理方法
extension PictureController: PhotoBrowserDismissDelegate {
    
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! PictureCell
        
        iv.image = cell.imageView.image
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        return iv
    }
    
    
    func indexPathForDismiss() -> NSIndexPath {
       
      return collectionView.indexPathsForVisibleItems()[0]
    }
}

//
extension PictureController:  UICollectionViewDataSource{
    
    //设置collocationView
    private func prepareForCollectionView(){
        collectionView.dataSource = self
        collectionView.registerClass(PictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        
    }
    
    //自定义流水布局
    private class PictureFlowLayout: UICollectionViewFlowLayout{
        
        //重写prepareLayout自定义cell布局
        private override func prepareLayout() {
            super.prepareLayout()

            itemSize = collectionView!.bounds.size
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.bounces = false

        }
    }
}

//数据源方法和代理方法
extension PictureController {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! PictureCell
        cell.imageUrl = urls[indexPath.row]
        cell.delegate = self
        return cell
    }
}

//MARK: 实现Cell代理方法
extension PictureController: PictureCellDelgate {
    
    ///点击图片关闭控制器
    func pictureCellclickImage() {
        closeController()
    }
    
    ///实现交互式过场动画
    func pictureCellDidZoom(scacle: CGFloat) {
        
        //判断是否交互
        let isHidden = scacle < 1
        
        //判断是否隐藏控件
        hiddenController(isHidden)
        
        //如果缩小
        if scacle < 1 {
            view.alpha = scacle
            view.transform = CGAffineTransformMakeScale(scacle, scacle)
        }else{
            view.alpha = 1
            view.transform = CGAffineTransformIdentity
        }
      
    }
    
    //隐藏控制器的view
    func hiddenController(isHidden: Bool){
        saveButton.hidden = isHidden
        closeButton.hidden = isHidden
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    }
}